package com.appbee.gdata.picasa.client.activity;

import java.util.List;

import javax.inject.Inject;

import com.appbee.cm.client.regionunit.presenter.HasActivityEntry;
import com.appbee.cm.shared.data.ActivityEntryProxy;
import com.appbee.gdata.picasa.shared.PicasaRequestFactory;
import com.appbee.gdata.picasa.shared.SimplePhotoProxy;
import com.google.gwt.activity.shared.AbstractActivity;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.user.client.ui.AcceptsOneWidget;
import com.google.gwt.user.client.ui.IsWidget;
import com.google.web.bindery.requestfactory.shared.Receiver;
import com.google.web.bindery.requestfactory.shared.Request;

public class PicasaPhotoShowActivity extends AbstractActivity implements
		HasActivityEntry
{

	public interface View extends IsWidget
	{

		void setPhotoUrl(String url);

	}

	private final View view;
	private final PicasaRequestFactory serviceProvider;
	private ActivityEntryProxy activityEntry;
	private final Scheduler scheduler;
	private int index;
	private boolean running = true;

	@Inject
	public PicasaPhotoShowActivity(	View view,
									PicasaRequestFactory serviceProvider,
									Scheduler scheduler)
	{
		this.view = view;
		this.serviceProvider = serviceProvider;
		this.scheduler = scheduler;
	}

	@Override
	public void start(AcceptsOneWidget panel, EventBus eventBus)
	{
		Request<List<SimplePhotoProxy>> request = serviceProvider
				.getPicasaService().findPhotos(	activityEntry.getSettings(),
												0,
												10);

		request.fire(new Receiver<List<SimplePhotoProxy>>()
		{

			@Override
			public void onSuccess(final List<SimplePhotoProxy> response)
			{
				// Do nothing if empty.
				if (response.isEmpty())
					return;

				index = 0;
				view.setPhotoUrl(response.get(index).getUrl());
				scheduler.scheduleFixedPeriod(new Scheduler.RepeatingCommand()
				{

					@Override
					public boolean execute()
					{
						index++;
						if (index >= response.size())
							index = 0;
						view.setPhotoUrl(response.get(index).getUrl());
						return running;
					}
				}, 1000 * 7);
			}

		});
		panel.setWidget(view);
	}

	@Override
	public void onStop()
	{
		running = false;
		super.onStop();
	}

	@Override
	public void setActivityEntry(ActivityEntryProxy activityEntry)
	{
		this.activityEntry = activityEntry;
	}

}
